<route lang="json5" type="page">
{
  layout: 'tabbar',
  needLogin: true,
  style: {
    navigationBarTitleText: '购物车',
  },
}
</route>

<script lang="ts" setup>
import { onShow } from '@dcloudio/uni-app'
import { ref, computed, defineAsyncComponent, watch } from 'vue'
import { useToast, useQueue, useMessage } from 'wot-design-uni'
import { getCartList, updateCart, deleteCart } from '@/service/goods/cart/cart'
import { useUserStore } from '@/store/user'
import type { CartItems, GoodsDiscountVO } from '@/service/goods/coupon/coupon.d'
import { calculateBestDiscount } from '@/service/goods/coupon/coupon'
import { GoodsSkuCartVo, GoodsCart } from '@/service/goods/cart/cart.d'
import { GoodsSku } from '@/service/goods/goods.d'
import { useActiveCartStore } from '@/store/activeCart'
import { debounce } from 'lodash-es'

const activeCartStore = useActiveCartStore()
const CartBar = defineAsyncComponent(() => import('@/components/cartBar/index.vue'))
const SelectdProduct = defineAsyncComponent(() => import('@/components/selectdProduct/index.vue'))
const userStore = useUserStore()

const modelValue = ref(true)
const { closeOutside } = useQueue()
const message = useMessage()
const toast = useToast()
const params = ref({
  current: 1,
  size: 10,
})
const total = ref<number>(0)

const getCartListData = async () => {
  try {
    const { code, data } = await getCartList(params.value)
    if (code === 200 && data) {
      cartList.value = data.records
    }
  } catch (error) {
    toast.error('加载失败')
  }
}
const cartList = ref<GoodsSkuCartVo[]>([])

onShow(() => {
  getCartListData()
})

const selectedItems = computed<CartItems[]>(() => {
  const items: CartItems[] = []
  cartList.value.forEach((item) => {
    if (item.selected === 1) {
      items.push({ skuId: item.id, quantity: item.goodsNum })
    }
  })

  return items
})

const discountList = ref<GoodsDiscountVO[]>([])
const cartItemList = computed<GoodsCart[]>(() => {
  return cartList.value.map((item) => {
    const obj: GoodsCart = {
      selected: item.selected,
      skuId: item.id,
      goodsNum: item.goodsNum,
      customerId: item.customerId,
      id: item.cartId,
      goodsId: item.goodsId,
    }
    return obj
  })
})
// 带防抖的监听器（500ms防抖间隔）
watch(
  selectedItems,
  debounce((newVal) => {
    if (newVal.length > 0) {
      console.log('带防抖的监听器（500ms防抖间隔）', newVal)
      discountList.value = []
      calculateBestDiscount({
        userId: Number(userStore.userInfo.id),
        cartItems: newVal,
      }).then((res) => {
        console.log(res)
        if (res.code === 200 && res.data.length > 0) {
          discountList.value = res.data
          console.log(discountList)
        }
      })
    }
  }, 100),
  { deep: true },
)
watch(
  () => cartItemList.value,
  (newVal) => {
    const list = newVal.filter((item) => item.selected === 1)
    activeCartStore.setCart(list)
    console.log('监听到了:', newVal)
  },
  {
    deep: true,
  },
)

const JSONSpec = (str: string) => {
  const obj = JSON.parse(str)[0]
  console.log(Object.keys(obj))
  let valus = null

  Object.keys(obj).forEach((key) => {
    valus = obj[key]
    console.log(obj[key])
  })
  console.log(valus)
  return valus
}

const toggleSelect = async ({ value }, cartId: number) => {
  console.log(cartId, value)
  try {
    toast.loading('加载中...')
    const { code, data } = await updateCart({ id: cartId, selected: value })
    toast.close()
    if (code === 200 && data) {
      const item = cartList.value.find((item) => item.cartId === cartId)
      if (item) item.selected = value
    } else {
      throw new Error('修改失败')
    }
  } catch (error) {
    toast.error(error)
  }
}

const updateCartSpec = async (quantity: number, cartData: GoodsSku) => {
  try {
    toast.loading('加载中...')
    const { code, data } = await updateCart({
      skuId: cartData.id,
      goodsNum: quantity,
      id: activeCartId.value,
    })
    toast.close()
    if (code === 200 && data) {
      cartList.value = cartList.value.map((item) => {
        if (item.cartId === activeCartId.value) {
          return (item = { ...item, ...cartData })
        }
        return item
      })
    } else {
      throw new Error('修改失败')
    }
  } catch (error) {
    toast.error(error)
  }
}
const handelDeleteCart = (cartId: number) => {
  console.log(cartId)
  message
    .confirm({
      msg: '是否移出该商品？',
      title: '温馨提示',
    })
    .then(async () => {
      toast.loading('加载中...')
      const { code, data } = await deleteCart(cartId)
      toast.close()
      if (code === 200 && data) {
        params.value.current = 1
        getCartListData()
      } else {
        throw new Error('删除失败')
      }
    })
    .catch(() => {
      toast.error('删除失败')
    })
}
const SelectdProductRef = ref()
const activeCartId = ref()
const handelChangeSpec = (skuId: number, goodsId: number, cartId: number) => {
  SelectdProductRef.value.hanleOpen(skuId, goodsId)
  activeCartId.value = cartId
  modelValue.value = false
}

const closeChangeSpec = () => {
  modelValue.value = true
}

const changeQuantity = async ({ value }, cartId) => {
  console.log(1111)

  console.log(value, cartId)
  const item = cartList.value.find((item) => item.cartId === cartId)
  if (item) {
    try {
      value = Math.max(1, value)
      toast.loading('加载中')
      const { code, data } = await updateCart({ id: cartId, goodsNum: item.goodsNum })
      toast.close()
      if (code === 200 && data) {
        item.goodsNum = value
      } else {
        throw new Error('修改失败')
      }
    } catch (error) {
      toast.error(error)
    }
  }
}
const goGoods = () => {
  uni.navigateTo({
    url: `/pages/categorize/index`,
  })
}
</script>
<template>
  <view class="cart-page">
    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y v-if="cartList.length > 0">
      <view class="cart-box" v-for="item in cartList" :key="item.id" @click.stop="closeOutside">
        <wd-swipe-action>
          <view class="cart-item">
            <view class="item-left">
              <wd-checkbox
                :modelValue="item.selected"
                checked-color="#ff3737"
                :false-value="0"
                :true-value="1"
                @change="toggleSelect($event, item.cartId)"
              />
              <image class="product-image" :src="item.thumbImg" mode="aspectFill" />
            </view>

            <view class="item-right">
              <view class="product-info">
                <text class="product-title">{{ item.skuName }}</text>

                <text
                  class="product-spec"
                  @click="handelChangeSpec(item.id, item.goodsId, item.cartId)"
                >
                  {{ item.netContent }} * {{ JSONSpec(item.skuSpec) }}
                </text>

                <view class="product-price-cell">
                  <view class="product-price-box">
                    <text class="product-price">¥{{ item.salePrice }}</text>
                    <text class="product-marketPrice">¥{{ item.marketPrice }}</text>
                  </view>

                  <view class="product-actions">
                    <wd-input-number
                      v-model="item.goodsNum"
                      @change="changeQuantity($event, item.cartId)"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>
          <template #right>
            <view class="swipe-action" @click="handelDeleteCart(item.cartId)">
              <view class="button">删除</view>
            </view>
          </template>
        </wd-swipe-action>
      </view>
    </scroll-view>
    <SelectdProduct
      ref="SelectdProductRef"
      @updateCartSpec="updateCartSpec"
      @popClose="closeChangeSpec"
      :model-type="'cart'"
    />

    <!-- 底部操作栏 -->
    <CartBar
      v-if="discountList.length > 0"
      model-type="cart"
      :model-value="modelValue"
      :cart-list="cartItemList"
      :discount-list="discountList"
      bottom="120rpx"
    />
    <view
      v-if="cartList.length <= 0"
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        width: 750rpx;
        height: calc(100vh - 88rpx);
      "
    >
      <view style="display: flex; flex-direction: column; justify-content: center">
        <view style="margin-bottom: 20rpx; font-size: 28rpx; color: #999">
          去点杯美酒犒劳一下自己吧
        </view>
        <wd-button type="error" custom-class="custom-shadow" @click="goGoods">去选购</wd-button>
      </view>
    </view>
  </view>
</template>
<style lang="scss" scoped>
.cart-page {
  display: flex;
  flex-direction: column;
}

.cart-list {
  .cart-box {
    box-sizing: border-box;
    margin: 15rpx;
    overflow: hidden;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  }
  .cart-item {
    box-sizing: border-box;
    display: flex;
    width: 700rpx;
    padding: 16rpx;

    background: #fff;

    .item-left {
      display: flex;
      align-items: center;
      margin-right: 30rpx;

      .product-image {
        width: 150rpx;
        height: 150rpx;
        border-radius: 16rpx;
      }
    }

    .item-right {
      display: flex;
      flex: 1;
      flex-direction: column;
      justify-content: space-between;
      width: 400rpx;

      .product-info {
        .product-title {
          display: block;
          display: -webkit-box;
          margin-right: 10rpx;
          margin-bottom: 8rpx;
          overflow: hidden;
          font-size: 24rpx;
          line-height: 1.5;
          color: #333;
          text-overflow: ellipsis;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .product-spec {
          padding: 0 6px;
          font-size: 24rpx;
          color: #666;
          background-color: #d5d5d5;
          border-radius: 6rpx;
        }
        .product-price-cell {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .product-price-box {
            display: flex;
            align-items: center;
          }
        }

        .product-price {
          display: block;
          font-size: 32rpx;
          color: #e5492a;
        }
        .product-marketPrice {
          margin-left: 6rpx;
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
      }

      .product-actions {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-right: 12rpx;

        .quantity {
          margin: 0 30rpx;
          font-size: 28rpx;
        }
      }
    }
  }
  .swipe-action {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100rpx;
    height: 100%;
    font-size: 28rpx;
    color: #fff;
    background-color: #fe3227;
    border-top-right-radius: 24rpx;
  }
}
</style>
